/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: ServiceExporter
 * Author:   zengjian
 * Date:     2018/10/8 17:30
 * Description: 暴露的服务
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package org.yinxue.framework.rpc.register;


import org.yinxue.framework.rpc.RpcResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 〈暴露的服务〉<br> 
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/10/8 17:30
 */
public class ServiceExporter {

    /**
     * 暴露的服务名称  类名称_方法名_变量数量_版本号
     */
    private String serviceName;
    private Method method;
    private Object instance;
    private int version;

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Object getInstance() {
        return instance;
    }

    public void setInstance(Object instance) {
        this.instance = instance;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public RpcResponse invoke(Object...args) throws InvocationTargetException, IllegalAccessException {
        Object result = method.invoke(instance, args);
        return buildRpcResponse(result);
    }

    private RpcResponse buildRpcResponse(Object result) {
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setValue(result);
        rpcResponse.setType(method.getReturnType());
        return rpcResponse;
    }

    @Override
    public String toString() {
        return "ServiceExporter{" +
                "serviceName='" + serviceName + '\'' +
                ", method=" + method +
                ", instance=" + instance +
                ", version=" + version +
                '}';
    }
}